package org.tgcloud.group.web.controller.manager.export;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.BeanUtil;
import org.tgcloud.group.core.DateUtil;
import org.tgcloud.group.core.session.Session;
import org.tgcloud.group.service.manager.ProjectManageService;
import org.tgcloud.group.web.controller.dto.medium.MediumAllProjectDTO;
import org.tgcloud.group.web.controller.dto.medium.MediumProjectMsgDTO;
import org.tgcloud.group.web.controller.manager.ManageAPPBaseController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: zhy
 * @Created: 2024-06-06-下午4:39
 * @Description:
 */
@Api(tags = "导出相关接口")
@RestController
@RequestMapping("/manager/pc/user")
@EnableAutoConfiguration
public class MediumDateExportManageController extends ManageAPPBaseController {

    @Autowired
    private ProjectManageService projectManageService;

    public static String[] headList = {"媒体", "ID"};

    public static String[] headValueList = {"name", "id"};

    @ApiOperation(value = "媒体日历导出")
    @ApiImplicitParams({
    })
    @ApiResponses({
            @ApiResponse(code = 2000, message = "出现异常，及时通知后台")
    })
    @ResponseBody
    @PostMapping(value = "/doExportMediumDate")
    public void doExportMediumDateFile(HttpServletResponse response,
                             @RequestParam Long startTime,
                             @RequestParam Long endTime,
                                       @ModelAttribute("session") Session session) throws Exception{
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        String excelName = dateFormat.format(new Date(startTime)) + "-" + dateFormat.format(new Date(endTime)) + "媒体日历";
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8") + ".xlsx");
        response.addHeader("filename", URLEncoder.encode(excelName, "UTF-8"));
        try {
            OutputStream out = response.getOutputStream();
            List<Date> dateListByStartTimeAndEndTime = DateUtil.getDateListByStartTimeAndEndTime(new Date(startTime), new Date(endTime));
            List<JSONObject> jsonObjectList = new ArrayList<>();
            List<String> headerList = new ArrayList<>();
            headerList.add("媒体");
            for (Date date : dateListByStartTimeAndEndTime){
                headerList.add(DateUtil.getyyyy_MM_dd(date));
            }
            APPResultMessage appResultMessage = projectManageService.viewOfflineHasPackageProjectList(new Date(startTime), new Date(endTime), null, null, null, null, null, null, session.getComId());
            if (appResultMessage.getKey() == 1000){
                List<MediumAllProjectDTO> list = (List<MediumAllProjectDTO>) appResultMessage.getResult().getList();
                for (MediumAllProjectDTO dto : list){
                    for (int i = 0; i< dto.getNum(); i ++){
                        JSONObject jsonObject = new JSONObject();
                        for (int h =0;h<headList.length;h++){
                            Field declaredField = dto.getClass().getSuperclass().getDeclaredField(headValueList[h]);
                            declaredField.setAccessible(true);
                            Object fieldValue = declaredField.get(dto);
                            jsonObject.put(headList[h], fieldValue);
                        }
                        for (Date date : dateListByStartTimeAndEndTime){
                            jsonObject.put(DateUtil.getyyyy_MM_dd(date), null);
                        }
                        jsonObject.put("areaType", 1);
                        jsonObjectList.add(jsonObject);
                    }
                    for (int i = 0; i< dto.getLineUpNum(); i ++){
                        JSONObject jsonObject = new JSONObject();
                        for (int h =0;h<headList.length;h++){
                            Field declaredField = dto.getClass().getSuperclass().getDeclaredField(headValueList[h]);
                            declaredField.setAccessible(true);
                            Object fieldValue = declaredField.get(dto);
                            String value = String.valueOf(fieldValue);
                            if (!value.equals("ID")){
                                value = value + "\n排队位";
                            }
                            jsonObject.put(headList[h], value);
                        }
                        for (Date date : dateListByStartTimeAndEndTime){
                            jsonObject.put(DateUtil.getyyyy_MM_dd(date), null);
                        }
                        jsonObject.put("areaType", 2);
                        jsonObjectList.add(jsonObject);
                    }
                }
                for (MediumAllProjectDTO dto : list){
                    if (!BeanUtil.isNullList(dto.getProjectMsgDTOList())){
                        for (int i = 0; i< jsonObjectList.size(); i ++){
                            if (jsonObjectList.get(i).get("ID").equals(dto.getId())){
                                for (MediumProjectMsgDTO mediumProjectMsgDTO : dto.getProjectMsgDTOList()) {
                                    Integer z = mediumProjectMsgDTO.getLineIndex();
                                    if (mediumProjectMsgDTO.getChooseTime() != null && mediumProjectMsgDTO.getChooseEndTime() != null
                                            && mediumProjectMsgDTO.getAddRecord() == 1) {
                                        List<Date> listByStartTimeAndEndTime = DateUtil.getDateListByStartTimeAndEndTime(mediumProjectMsgDTO.getChooseTime(), mediumProjectMsgDTO.getChooseEndTime());
                                        if (mediumProjectMsgDTO.getAreaType() == 1){
                                            boolean hasAdd = false;
                                            for (Date date : listByStartTimeAndEndTime) {
                                                if (jsonObjectList.get(i + z).get(DateUtil.getyyyy_MM_dd(date)) != null) {
                                                    hasAdd = true;
                                                }
                                            }
                                            if (!hasAdd) {
                                                for (Date date : listByStartTimeAndEndTime) {
                                                    Integer addIndex = i + z;
                                                    if (jsonObjectList.get(i + z).get("ID").equals(jsonObjectList.get(i + z).get("ID"))) {
                                                        addIndex = i + z;
                                                    }
                                                    jsonObjectList.get(addIndex).put(DateUtil.getyyyy_MM_dd(date), mediumProjectMsgDTO);
                                                }
                                                mediumProjectMsgDTO.setAddRecord(2);
                                            }
                                        } else {
                                            boolean hasAdd = false;
                                            for (Date date : listByStartTimeAndEndTime) {
                                                if (jsonObjectList.get(i + z + dto.getNum()).get(DateUtil.getyyyy_MM_dd(date)) != null) {
                                                    hasAdd = true;
                                                }
                                            }
                                            if (!hasAdd) {
                                                for (Date date : listByStartTimeAndEndTime) {
                                                    Integer addIndex = i + z + dto.getNum();
                                                    if (jsonObjectList.get(i + z + dto.getNum()).get("ID").equals(jsonObjectList.get(i + z + dto.getNum()).get("ID"))) {
                                                        addIndex = i + z + dto.getNum();
                                                    }
                                                    jsonObjectList.get(addIndex).put(DateUtil.getyyyy_MM_dd(date), mediumProjectMsgDTO);
                                                }
                                                mediumProjectMsgDTO.setAddRecord(2);
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
            getExportListExcel(excelName, out, headerList, jsonObjectList);
            out.close();
            System.out.println("excel导出成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public void getExportListExcel(String title, OutputStream out, List<String> headerList,
                                      List<JSONObject> exportList) throws Exception{
        //声明一个工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建一个全局样式，启用自动换行
        CellStyle wrapStyle = workbook.createCellStyle();
        wrapStyle.setWrapText(true); // 启用自动换行
        //生成一个表格
        XSSFSheet sheet = workbook.createSheet(title);
        //设置表格默认列宽度为15个字符
        sheet.setDefaultColumnWidth(12);
        sheet.setDefaultRowHeight((short) 10);
        sheet.setDefaultRowHeightInPoints(10);

        // 生成并设置另一个样式,用于设置内容样式
        XSSFCellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
        // 填充效果（全景填充）
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置边框
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        headerStyle.setBorderTop(BorderStyle.THIN);
        // 生成另一个字体
        XSSFFont font2 = workbook.createFont();
        font2.setColor(IndexedColors.BLACK.getIndex());
        font2.setBold(true);
        font2.setFontHeightInPoints((short) 11);
        font2.setFontName("微软雅黑");
        headerStyle.setFont(font2);
        headerStyle.setWrapText(true); // 自动换行

        XSSFFont sureTypeFont = workbook.createFont();
        sureTypeFont.setColor(IndexedColors.BLACK.getIndex());
        sureTypeFont.setFontHeightInPoints((short) 11);
        sureTypeFont.setFontName("微软雅黑");

        // 已确认
        XSSFCellStyle sureStyle = workbook.createCellStyle();
//        sureStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(52,181,98)));
        sureStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(144, 238, 144)));
        sureStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        sureStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        sureStyle.setBorderBottom(BorderStyle.THIN);
        sureStyle.setBorderLeft(BorderStyle.THIN);
        sureStyle.setBorderRight(BorderStyle.THIN);
        sureStyle.setBorderTop(BorderStyle.THIN);
        sureStyle.setWrapText(true); // 自动换行
        sureStyle.setFont(sureTypeFont);

        // 审核中，暂定，已签
        XSSFCellStyle noSureStyle = workbook.createCellStyle();
//        noSureStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        noSureStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(250, 250, 210)));
        noSureStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        noSureStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        noSureStyle.setBorderBottom(BorderStyle.THIN);
        noSureStyle.setBorderLeft(BorderStyle.THIN);
        noSureStyle.setBorderRight(BorderStyle.THIN);
        noSureStyle.setBorderTop(BorderStyle.THIN);
        noSureStyle.setWrapText(true); // 自动换行
        noSureStyle.setFont(sureTypeFont);

        // 未签
        XSSFCellStyle notSignStyle = workbook.createCellStyle();
        notSignStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(211, 211, 211)));
        notSignStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        notSignStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        notSignStyle.setBorderBottom(BorderStyle.THIN);
        notSignStyle.setBorderLeft(BorderStyle.THIN);
        notSignStyle.setBorderRight(BorderStyle.THIN);
        notSignStyle.setBorderTop(BorderStyle.THIN);
        notSignStyle.setWrapText(true); // 自动换行
        notSignStyle.setFont(sureTypeFont);

        Integer rowNum = 1;
        XSSFRow row = sheet.createRow(rowNum);
        row.setHeightInPoints(20);
        for (int i = 0; i < headerList.size(); i++){
            XSSFCell cell = row.createCell(i);
            cell.setCellStyle(headerStyle);
            XSSFRichTextString text = new XSSFRichTextString(headerList.get(i));
            cell.setCellValue(text);
        }
        if (!BeanUtil.isNullList(exportList)){
            for (JSONObject jsonObject : exportList) {
                rowNum = rowNum + 1;
                row = sheet.createRow(rowNum);
                for (int z = 0; z < headerList.size(); z++) {
                    String key = headerList.get(z);
                    Object o = jsonObject.getObject(key, Object.class);
                    XSSFCell cell = row.createCell(z);
                    if (o != null){
                        String v = o.toString();
                        cell.setCellValue(v);
                        if (o instanceof MediumProjectMsgDTO){
                            MediumProjectMsgDTO dto = (MediumProjectMsgDTO) o;
                            if (dto.getSureType() != null){
                                if (dto.getSureType() == 5){
                                    cell.setCellStyle(sureStyle);
                                }else if (dto.getSureType() == 1 || dto.getSureType() == 2 || dto.getSureType() == 4){
                                    cell.setCellStyle(noSureStyle);
                                }else if (dto.getSureType() == 3){
                                    cell.setCellStyle(notSignStyle);
                                }
                            }
                            v = dto.getBrands() + "\n" + dto.getCreateUserName();
                            cell.setCellValue(v);
                        }
                    }else {
                        cell.setCellValue("");
                    }
                }
            }
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
